﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ROrganizer.UI.Controllers;
using ROrganizer.UI.Forms.Core;
using ROrganizer.UI.Properties;

namespace ROrganizer.UI.Forms
{
    internal partial class CreateUserForm : Form
    {
        private readonly CreateUserFormController controller;

        public CreateUserForm()
        {
            this.controller = new CreateUserFormController();
            this.InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.pbRefresh.Image = Resources.RefreshGreen;
            this.pbCaptcha.Image = this.controller.Image;
            this.btnCreate.Enabled = this.controller.CanCreate();
        }

        private void OnUsernameChanged(object sender, EventArgs e)
        {
            this.controller.Username = this.tbUsername.Text.Trim();
            this.btnCreate.Enabled = this.controller.CanCreate();
        }

        private void OnPasswordChanged(object sender, EventArgs e)
        {
            this.controller.Password = this.tbPassword.Text.Trim();
            this.btnCreate.Enabled = this.controller.CanCreate();
        }

        private void OnPasswordRetyped(object sender, EventArgs e)
        {
            this.controller.Retyped = this.tbRetypePassword.Text.Trim();
            this.btnCreate.Enabled = this.controller.CanCreate();
        }

        private void OnCaptchaChanged(object sender, EventArgs e)
        {
            this.controller.Captcha = this.tbCaptcha.Text.Trim();
            this.btnCreate.Enabled = this.controller.CanCreate();
        }

        private void OnCreateAccount(object sender, EventArgs e)
        {
            this.ExecuteAndWatch(this.CreateAccount);
        }

        private void CreateAccount()
        {
            if (this.controller.Create())
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show(this, "Can't create account!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.tbCaptcha.Text = this.controller.Captcha;
                this.pbCaptcha.Image = this.controller.Image;
            }
        }

        private void OnRefreshCaptcha(object sender, EventArgs e)
        {
            this.ExecuteAndWatch(this.RefreshCaptcha);
        }

        private void RefreshCaptcha()
        {
            this.controller.Refresh();
            this.pbCaptcha.Image = this.controller.Image;
            this.tbCaptcha.Text = this.controller.Captcha;
        }
    }
}
